package com.le.sarrs.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;


/**
 * @author gaojiawei
 */
public final class HttpToolkit {
    private static Logger log = LoggerFactory.getLogger(HttpToolkit.class);
    private static String defaultContentEncoding = Charset.defaultCharset().name();

    public static boolean urlExists(final String URLName) {
        try {
            // 设置此类是否应该自动执行 HTTP 重定向（响应代码为 3xx 的请求）。
            HttpURLConnection.setFollowRedirects(false);
            // 到 URL 所引用的远程对象的连接
            HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
            con.setConnectTimeout(200);
            /*
			 * 设置 URL 请求的方法， GET POST HEAD OPTIONS PUT DELETE TRACE
			 * 以上方法之一是合法的，具体取决于协议的限制。
			 */
            con.setRequestMethod("HEAD");
            // 从 HTTP 响应消息获取状态码
            return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 发送GET请求
     *
     * @param urlString URL地址
     * @return 响应对象
     * @throws IOException
     */
    public static String sendGet(final String urlString) {
        return send(urlString, "GET", 200, 2000, null, null);
    }

    public static String sendGet(final String urlString, final int timeout) {
        return send(urlString, "GET", timeout, 2000, null, null);
    }

    public static String sendGet(final String urlString, final int connTimeout, final int readTimeout) {
        return send(urlString, "GET", connTimeout, readTimeout, null, null);
    }

    /**
     * 发送GET请求
     *
     * @param urlString URL地址
     * @param params    参数集合
     * @return 响应对象
     * @throws IOException
     */
    public static String sendGet(final String urlString, final Map<String, String> params) {
        return send(urlString, "GET", params, null);
    }

    /**
     * 发送GET请求
     *
     * @param urlString URL地址
     * @param params    参数集合
     * @param propertys 请求属性
     * @return 响应对象
     * @throws IOException
     */
    public static String sendGet(final String urlString, final Map<String, String> params,
                                 final Map<String, String> propertys) {
        return send(urlString, "GET", params, propertys);
    }

    /**
     * 发送POST请求
     *
     * @param urlString URL地址
     * @return 响应对象
     * @throws IOException
     */
    public static String sendPost(final String urlString) {
        return send(urlString, "POST", null, null);
    }

    /**
     * 发送POST请求
     *
     * @param urlString URL地址
     * @param params    参数集合
     * @return 响应对象
     * @throws IOException
     */
    public static String sendPost(final String urlString, final Map<String, String> params) {
        return send(urlString, "POST", params, null);
    }

    /**
     * 发送POST请求
     *
     * @param urlString URL地址
     * @param params    参数集合
     * @param propertys 请求属性
     * @return 响应对象
     * @throws IOException
     */
    public static String sendPost(final String urlString, final Map<String, String> params,
                                  final Map<String, String> propertys) {
        return send(urlString, "POST", params, propertys);
    }


    public static String sendPost(final String urlString, final int connTimeout, final int readTimeout, final Map<String, String> params,
                                  final Map<String, String> propertys) {
        return send(urlString, "POST", connTimeout, readTimeout, params, propertys);
    }

    /**
     * 发送HTTP请求
     *
     * @param urlString
     * @return 响映对象
     * @throws IOException
     */
    private static String send(String urlString, final String method,
                               final Map<String, String> parameters, final Map<String, String> propertys) {
        try {
            HttpURLConnection urlConnection = null;
            if (method.equalsIgnoreCase("GET") && parameters != null) {
                StringBuffer param = new StringBuffer();
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i == 0) {
                        param.append("?");
                    } else {
                        param.append("&");
                    }
                    param.append(key).append("=").append(parameters.get(key));
                    i++;
                }
                urlString += param;
            }
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(1000);
            urlConnection.setReadTimeout(1000);
            urlConnection.setRequestMethod(method);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);

            if (propertys != null) {
                for (String key : propertys.keySet()) {
                    urlConnection.addRequestProperty(key, propertys.get(key));
                }
            }

            if (method.equalsIgnoreCase("POST") && parameters != null) {
                StringBuffer param = new StringBuffer();
                for (String key : parameters.keySet()) {
                    param.append("&");
                    param.append(key).append("=").append(parameters.get(key));
                }
                urlConnection.getOutputStream().write(param.toString().getBytes());
                urlConnection.getOutputStream().flush();
                urlConnection.getOutputStream().close();
            }

            return makeContent(urlString, urlConnection);
        } catch (Exception e) {
            log.warn(e.getMessage());
            return "{}";
        }
    }

    private static String send(String urlString, final String method, final int timeout,
                               final Map<String, String> parameters, final Map<String, String> propertys) {
        try {
            HttpURLConnection urlConnection = null;
            if (method.equalsIgnoreCase("GET") && parameters != null) {
                StringBuffer param = new StringBuffer();
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i == 0) {
                        param.append("?");
                    } else {
                        param.append("&");
                    }
                    param.append(key).append("=").append(parameters.get(key));
                    i++;
                }
                urlString += param;
            }
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(timeout);
            urlConnection.setReadTimeout(timeout);
            urlConnection.setRequestMethod(method);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);

            if (propertys != null) {
                for (String key : propertys.keySet()) {
                    urlConnection.addRequestProperty(key, propertys.get(key));
                }
            }

            if (method.equalsIgnoreCase("POST") && parameters != null) {
                StringBuffer param = new StringBuffer();
                for (String key : parameters.keySet()) {
                    param.append("&");
                    param.append(key).append("=").append(parameters.get(key));
                }
                urlConnection.getOutputStream().write(param.toString().getBytes());
                urlConnection.getOutputStream().flush();
                urlConnection.getOutputStream().close();
            }

            return makeContent(urlString, urlConnection);
        } catch (Exception e) {

            log.warn("http request process error!", e);
            return "{}";
        }
    }

    private static String send(String urlString, final String method, final int connTimeout, final int readTimeout,
                               final Map<String, String> parameters, final Map<String, String> propertys) {
        try {
            HttpURLConnection urlConnection = null;
            if (method.equalsIgnoreCase("GET") && parameters != null) {
                StringBuffer param = new StringBuffer();
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i == 0) {
                        param.append("?");
                    } else {
                        param.append("&");
                    }
                    param.append(key).append("=").append(parameters.get(key));
                    i++;
                }
                urlString += param;
            }
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(connTimeout);
            urlConnection.setReadTimeout(readTimeout);
            urlConnection.setRequestMethod(method);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);

            if (propertys != null) {
                for (String key : propertys.keySet()) {
                    urlConnection.addRequestProperty(key, propertys.get(key));
                }
            }

            if (method.equalsIgnoreCase("POST") && parameters != null) {
                StringBuffer param = new StringBuffer();
                for (String key : parameters.keySet()) {
                    param.append("&");
                    param.append(key).append("=").append(parameters.get(key));
                }
                urlConnection.getOutputStream().write(param.toString().getBytes());
                urlConnection.getOutputStream().flush();
                urlConnection.getOutputStream().close();
            }

            return makeContent(urlString, urlConnection);
        } catch (Exception e) {
            String flag = urlString.length() > 150 ? urlString.substring(0, 150) : urlString;
            log.warn("http request process error! url=" + flag + "...", e);
//    			e.printStackTrace();
            return "{}";
        }
    }

    public static String sendPostJsonStream(final String urlString, final int connTimeout, final int readTimeout, final Map<String, String> params,
                                            final Map<String, String> propertys, String jsonContent) {
        return postJson(urlString, "POST", connTimeout, readTimeout, params, propertys, jsonContent);
    }

    private static String postJson(String urlString, final String method, final int connTimeout, final int readTimeout,
                                   final Map<String, String> parameters, final Map<String, String> propertys, String jsonContent) {
        try {
            HttpURLConnection urlConnection = null;
            if (method.equalsIgnoreCase("POST") && parameters != null) {
                StringBuffer param = new StringBuffer();
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i == 0) {
                        param.append("?");
                    } else {
                        param.append("&");
                    }
                    param.append(key).append("=").append(parameters.get(key));
                    i++;
                }
                urlString += param;
            }
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(connTimeout);
            urlConnection.setReadTimeout(readTimeout);
            urlConnection.setRequestMethod(method);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);

            if (propertys != null) {
                for (String key : propertys.keySet()) {
                    urlConnection.addRequestProperty(key, propertys.get(key));
                }
            }

            if (method.equalsIgnoreCase("POST") && jsonContent != null) {
                urlConnection.getOutputStream().write(jsonContent.getBytes());
//	    			urlConnection.getOutputStream().write(param.toString().getBytes());
                urlConnection.getOutputStream().flush();
                urlConnection.getOutputStream().close();
            }

            return makeContent(urlString, urlConnection);
        } catch (Exception e) {
            String flag = urlString.length() > 150 ? urlString.substring(0, 150) : urlString;
            log.warn("http request process error! url=" + flag + "...", e);
//    			e.printStackTrace();
            return "{}";
        }
    }


    /**
     * 得到响应对象
     *
     * @param urlConnection
     * @return 响应对象
     * @throws IOException
     */
    private static String makeContent(final String urlString,
                                      final HttpURLConnection urlConnection) throws IOException {
        try {
            InputStream in = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(in, "UTF-8"));
            StringBuffer temp = new StringBuffer();
            String line = bufferedReader.readLine();
            while (line != null) {
                temp.append(line).append("\n");
                line = bufferedReader.readLine();
            }
            bufferedReader.close();

            String ecod = urlConnection.getContentEncoding();
            if (ecod == null) {
                ecod = HttpToolkit.defaultContentEncoding;
            }
//    			String flag = urlString.length() >100 ? urlString.substring(0, 100) :urlString;
            log.debug("http-request-get " + urlString + "...  ok.");
            return new String(temp.toString().getBytes(), ecod);

        } catch (IOException e) {
            throw e;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String url = "http://106.38.226.220/sarrs/apirec_json.so?appname=leview&cid=n0&from=mobile&lc=861545033038151&platform=1&user_setting_country=CN&versiontype=LeJianNews&area=rec_0903&brand=LeEco&sales_area=CN&version=2.2.4.0725&lang=zh_CN&uid=190196967&terminalSeries=Le_X620_whole-netcom&sso_tk=103de00a19jFH4lz0JhYw8AFVyz2ko8qci02L7VwOMPnGonExEtNtRo23ObnRSKsHj5wTyQA&variant=lejian";
        for (int i = 0; i < 100; i++) {
            String content = HttpToolkit.sendGet(url);
        }
        System.out.println(System.currentTimeMillis() - start);


    }
}